/*
 * adc.cpp
 *
 *  Created on: Jun 25, 2013
 *      Author: r.leonov
 */

#include "adc.h"

Adc_t Adc;

void Adc_t::Init(){
    PinSetupAnalog(GPIOA, 2, pudNone);


    RCC->CR |= RCC_CR_HSION;                // Enable HSI
    while(!((RCC->CR) & RCC_CR_HSIRDY));     // Wait while HSI enable
    RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;     // Enable ADC1 RCC
    ADC1->CR2 = ADC_CR2_ADON;               // Wake Up ADC
    while(!((ADC1->SR) & ADC_CSR_ADONS1));  // Wait while RCC enable
    ADC1->SQR5 |= ADC_SQR5_SQ1_1;           // Choose channel 2 and 1st conversion in regular sequence
    ADC1->CR1 &= ~ADC_CR1_RES;              // 12 bit

    ADC1->CR2 |= ADC_CR2_SWSTART;           // Start conversations
    Value = 0;
    TresholdState = false;
}

void Adc_t::Task(){
    if(Delay.Elapsed(&Timer, 251)){
        ADC1->CR2 |= ADC_CR2_SWSTART;   // Start conversations
        Value = (3300*(ADC1->DR))/4096;
//        Uart.Printf("%u mV\r", Value);
        if(Value > TRESHOLD) TresholdState = true;
        else TresholdState = false;
    }
}
